<?php

namespace app\admin\controller\billiard\store;

use app\common\controller\Backend;
use app\common\model\mycurrency\LeaseStrategy;
use app\common\model\mycurrency\MerchantStore;
use app\common\model\billiard\Goods as GoodsModel;
use think\Db;
use think\Exception;

/**
 * 共享台球柜-门店-绑定商品管理
 *
 * @icon fa fa-circle-o
 */
class Goods extends Backend
{

    /**
     * Goods模型对象
     * @var \app\admin\model\billiard\store\Goods
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\billiard\store\Goods;

    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['store','strategy','goodsp'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                
                $row->getRelation('store')->visible(['store_name']);
				$row->getRelation('strategy')->visible(['title','types','duration','unit_price','free_duration','free_frequency','free_cycle']);
				$row->getRelation('goodsp')->visible(['title']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }


    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }

        // 验证必要参数
        $rule = [
            ['store_id', 'require', '门店ID不能为空'],
            ['goods_id', 'require', '系统产品id不能为空'],
            ['advance_fee', 'require', '预付金不能为空'],
            ['duration', 'require', '收费标准时长不能为空'],
            ['unit_price', 'require', '收费标准价格不能为空'],
        ];
        
        $validate = new \think\Validate($rule);
        $result = $validate->check($params);
        if (!$result) {
            $this->error($validate->getError());
        }

        // 获取门店和商品信息
        $store = MerchantStore::get($params['store_id']);
        if (!$store) {
            $this->error('门店不存在');
        }
        
        $goods = GoodsModel::where(['id' => $params['goods_id'], 'deletetime' => null])->find();
        if (!$goods) {
            $this->error('产品不存在');
        }
        
        if ($goods['status'] == GoodsModel::STATUS_JINYONG) {
            $this->error('产品不可用');
        }
        
        // 检查该门店是否已经添加了这个商品
        if (\app\common\model\billiard\StoreGoods::where([
            'store_id' => $params['store_id'],
            'goods_id' => $goods->id,
            'deletetime' => null
        ])->find()) {
            $this->error('产品已经存在请勿重复添加');
        }
        
        // 开始事务
        Db::startTrans();
        try {
            // 添加计费策略
            $strategy_increase = [
                'title' => "{$store->store_name}-{$goods->title}【收费标准】",
                'types' => LeaseStrategy::TYPES_SHICHANG,
                'duration' => $params['duration'],
                'unit_price' => $params['unit_price'],
                'free_duration' => 0,
                'free_frequency' => 0,
                'free_cycle' => 0,
                'overtime_money' => 0,
                'overtime_company' => 0,
                'status' => LeaseStrategy::STATUS_ZHENGCHENG,
                'createtime' => time(),
            ];
            $strategy = LeaseStrategy::create($strategy_increase);
            
            // 添加门店商品记录
            $increase = [
                'store_id' => $params['store_id'],
                'lease_strategy_id' => $strategy->id,
                'goods_id' => $goods->id,
                'advance_fee' => $params['advance_fee'],
                'createtime' => time(),
            ];
            \app\common\model\billiard\StoreGoods::create($increase);
            
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        
        $this->success('添加成功');
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /**
     * 删除
     *
     * @param $ids
     * @return void
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function del($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = $this->model->where($pk, 'in', $ids)->select();

        $count = 0;
        Db::startTrans();
        try {
            foreach ($list as $item) {
                $count += $item->delete();
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }


}
